import debounce from 'lodash/debounce';
import { useMemo, useState } from 'react';
import { filterListOrTree } from './utils';

export function useDebouncedSearch<T>(
  dataSource: T[] | undefined,
  filterFunc: (keywords: string, data: T) => boolean,
  wait: number = 300,
  filterLeaf: boolean = false
) {
  const [keywords, setKeywords] = useState('');
  const filteredData = useMemo(
    () =>
      dataSource && keywords.trim()
        ? filterListOrTree(dataSource, keywords, filterFunc, filterLeaf)
        : dataSource,
    [dataSource, keywords, filterFunc, filterLeaf]
  );

  const debouncedSearch = useMemo(() => {
    const search = (e) => {
      setKeywords(e.target.value);
    };
    return debounce(search, wait);
  }, [wait]);

  return {
    keywords,
    filteredData,
    debouncedSearch,
  };
}

// 用法
let data = [
  {
    id: 1,
    label: '一级 1',
    children: [
      {
        id: 4,
        label: '二级 1-1',
        children: [
          {
            id: 9,
            label: '三级 1-1-1',
          },
          {
            id: 10,
            label: '三级 1-1-2',
          },
        ],
      },
    ],
  },
  {
    id: 2,
    label: '一级 2',
    children: [
      {
        id: 5,
        label: '二级 2-1',
      },
      {
        id: 6,
        label: '二级 2-2',
      },
    ],
  },
  {
    id: 3,
    label: '一级 3',
    children: [
      {
        id: 7,
        label: '二级 3-1',
      },
      {
        id: 8,
        label: '二级 3-2',
      },
    ],
  },
];
const { filteredData, debouncedSearch } = useDebouncedSearch(
  data,
  (keywords, d) => d.label.toLowerCase().includes(keywords.toLowerCase())
);
